package com.tsugun.mediaplayer.view.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.model.entity.AlbumModel;
import com.tsugun.mediaplayer.model.entity.MusicModel;
import com.tsugun.mediaplayer.view.loader.MediaImageLoad;

import java.util.ArrayList;
import java.util.List;

import static com.tsugun.mediaplayer.presenter.utils.SettingPreferenceHelper.*;

/**
 * 卡片列表项目适配器
 * Created by shize on 2017/4/11.
 */

public class AlbumItemAdapter extends RecyclerView.Adapter<AlbumItemAdapter.CardItemViewHolder> {

    private LayoutInflater mInflater;
    private List<AlbumModel> mData;
    private OnAlbumItemClickListener mOnAlbumItemClickListener;
    private List<String> mPosList; // 记录滑动后需要缓存的item，防止重复加载已经加载的图片影响用户体验

    private boolean mOnScroll; // 是否正在滑动

    public interface OnAlbumItemClickListener {
        void onItemClick(View v, int position);
    }

    public AlbumItemAdapter(Context context, List<AlbumModel> data) {
        mData = data;
        mPosList = new ArrayList<>();
        mInflater = LayoutInflater.from(context);
        mOnScroll = false;
    }

    public void setOnAlbumItemClickListener(OnAlbumItemClickListener onAlbumItemClickListener) {
        mOnAlbumItemClickListener = onAlbumItemClickListener;
    }

    @Override
    public CardItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new CardItemViewHolder(mInflater.inflate(R.layout.item_album, parent, false));
    }

    @Override
    public void onBindViewHolder(final CardItemViewHolder holder, int position) {
        AlbumModel album = mData.get(position);
        holder.mTvTitle.setText(album.getName());
        holder.mTvArtist.setText(album.getArtist());
        loadImage(holder, album);
        setListener(holder);
        // 设置主题
        setSettingTheme(holder);
    }

    /**
     * 加载图片
     */
    private void loadImage(CardItemViewHolder holder, AlbumModel album) {
        if (mOnScroll) {
            addLoadItem(holder);
            holder.mIvIcon.setImageResource(R.color.grey_400);
            return;
        }
        holder.mIvIcon.setImageResource(R.drawable.ic_music_default);
        MediaImageLoad.localImageLoad(new MusicModel(album.getMusicId(), album.getName(),
                album.getFirstMusicUrl()), holder.mIvIcon);
        removeLoadItem(holder);
    }

    /**
     * 设置监听器
     */
    private void setListener(final CardItemViewHolder holder) {
        if (mOnAlbumItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnAlbumItemClickListener.onItemClick(v, holder.getAdapterPosition());
                }
            });
        }
    }

    // 设置主题
    private void setSettingTheme(CardItemViewHolder holder) {
        holder.mTvTitle.setTextColor(INSTANCE.getTEXT_COLOR());
        holder.mRlAlbum.setBackgroundColor(INSTANCE.getBACKGROUND_COLOR());
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        // 拖拽滑动
                        mOnScroll = true;
                        break;
                    case RecyclerView.SCROLL_STATE_IDLE:
                        // 停止滑动
                        mOnScroll = false;
                        notifyItemLoadImage();
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        // 惯性滑动状态
                        break;
                }
            }
        });
    }

    /**
     * 通知item加载图片
     */
    private void notifyItemLoadImage() {
        for (int i = 0; i < mData.size(); i++) {
            if (mPosList.contains(String.valueOf(i))) {
                notifyItemChanged(i);
            }
        }
    }

    @Override
    public void onViewDetachedFromWindow(CardItemViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        removeLoadItem(holder);
    }

    /**
     * 移除需要加载图片的item
     */
    private void removeLoadItem(CardItemViewHolder holder) {
        String str = String.valueOf(holder.getAdapterPosition());
        if (mPosList.contains(str)) {
            mPosList.remove(str);
        }
    }

    /**
     * 添加需要加载图片的item
     */
    private void addLoadItem(CardItemViewHolder holder) {
        mPosList.add(String.valueOf(holder.getAdapterPosition()));
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    class CardItemViewHolder extends RecyclerView.ViewHolder {

        private ImageView mIvIcon;
        private TextView mTvTitle;
        private TextView mTvArtist;
        private RelativeLayout mRlAlbum;

        CardItemViewHolder(View itemView) {
            super(itemView);
            mIvIcon = (ImageView) itemView.findViewById(R.id.id_item_rounded_image);
            mTvTitle = (TextView) itemView.findViewById(R.id.id_item_card_title);
            mTvArtist = (TextView) itemView.findViewById(R.id.id_item_card_artist);
            mRlAlbum = (RelativeLayout) itemView.findViewById(R.id.id_item_album_bg);
        }
    }
}
